
#include "Base.h"

#include "Tools/DebugSystem.h"
#include "Game/Game.h"
#include "Game/GameTime.h"
#include "Entities/BaseEntity.h"
#include "Entities/Events/DebugToolEvents.h"

#include <Memory/DebugNew.h>

namespace CasaEngine
{

	/**
	 * 
	 */
	DebugSystem::DebugSystem(Game *pGame_) :
		IGameComponent(pGame_)
	{
		m_fFPSTime = 0.0f;
		m_fFPSLastDelta = 0.0f;
		m_iFPSCount = 0;
		m_iLastFPSCount = 0;
	}

	/**
	 * 
	 */
	DebugSystem::~DebugSystem()
	{
	}

	/**
	 * 
	 */
	void DebugSystem::Initialize()
	{
		
	}

	/**
	 * 
	 */
	void DebugSystem::Update( const GameTime& gameTime_ )
	{
		m_fFPSTime += gameTime_.FrameTime();
		m_iFPSCount++;
		
		if (m_fFPSTime >= 1.0f)
		{
			//AverageDrawCalls = drawCallThisSecond / m_iFPSCount;
			//AverageTrianglesDrawn = trianglesDrawnThisSecond / m_iFPSCount;
			//Reset startSecondTick and repaintCountSecond
			m_fFPSTime -= 1.0f;
			float FPSDelta = (float)m_iFPSCount * m_fFPSTime;			
			//FPS - delta, to reduce the calculation to 1 second precisely
			m_iLastFPSCount = (int)( (float)m_iFPSCount - FPSDelta + m_fFPSLastDelta );

			m_iFPSCount = 0;
			m_fFPSLastDelta = FPSDelta;
			//drawCallThisSecond = 0;
			//trianglesDrawnThisSecond = 0;

			FPSChangeEvent *pEvent = new FPSChangeEvent(m_iLastFPSCount);

			for (std::vector<BaseEntity *>::iterator it=m_Observers.begin();
				it != m_Observers.end();
				it++)
			{
				(*it)->GetComponentMgr()->HandleEvent(pEvent);
			}

			delete pEvent;
		}
	}

	/**
	 * 
	 */
	int DebugSystem::GetFPS() const
	{
		return m_iLastFPSCount;
	}

	/**
	 * 
	 */
	void DebugSystem::AddObserver(BaseEntity *pEntity_)
	{
		m_Observers.push_back(pEntity_);
	}

} // namespace CasaEngine
